<template>
    <div class="layout">
      <div class="header">
          <h2>仙食饮</h2>
          <h3>感觉生活不甜了，就喝杯奶茶呗；成年人的奶茶叫“微醺快乐水”</h3>
        <!-- <span class="rg"></span> -->
      </div>

      <div class="main">
        <div class="wrapper">
          <ul>
            <li>
              <div class="main-bottom">
                <ul>
                  <li class="tab" v-for="item in store.state.shuiguocha" style="display: flex;">
                    <p class="img"><img :src="item.imag" style="width: 50px;height: 50px;"></p>
                    <p @click="toDetail(shuiguocha)">{{
                      item.tea
                    }}&nbsp评分：{{ item.rating }}<br>{{ item.money }}元</p>
                    <div class="btn" @click="order(item)">加入购物车</div>
                  </li>

                </ul>
              </div>
            </li>
          </ul>
        </div>

        <!-- 购物车列表 -->
        <div class="cart-list">
          <li class="buycar" v-for="item in store.state.buycar.filter((item)=>item.num>0)">
            <p class="order">
            <div class="or">
              <p>{{ item.tea }}</p>
              <div style="display: flex;">
                <p>数量:{{ item.num || 1 }}</p>
                &nbsp;
                <p>
                  <el-button @click="jia(item.id)">+</el-button>
                  <el-button @click="jian(item.id)">-</el-button>
                </p>
              </div>

              <p>{{ item.num*item.money }}元</p>
            </div>
            </p>

          </li>
          <p>总数{{ totalNum }}</p>
          <p>总价：{{ totalPrice }}</p>
          <p @click="addData">立即支付</p>
          <p @click="clearAllCart">清空购物车</p>
        </div>
      </div>


    </div>
</template>

<script setup>
import { computed, onMounted, ref, reactive } from 'vue';
import '../store/index'
import store from '../store/index';
import $api from '@/api';
import { assign } from 'lodash';
import router from '@/router';
import axios from 'axios';
import { oppositeOrderMap } from 'element-plus/es/components/table-v2/src/constants';
import { ElMessage } from 'element-plus';
const activeName = ref('1')
const or = ref(1)
const total = ref()
const totalmoney = ref()
const formData = ref()


const toDetail = (e) => {
  console.log("=======>e", e);
  const { id } = (JSON.parse(JSON.stringify(e))[0])
  console.log("id", id);
  router.push({
    path: "/pay",
    query: { id: id }
  })
}
const shuiguocha = () => {
  return store.dispatch("getData")
}

onMounted(shuiguocha)

const buycar = computed(() => {
  return store.dispatch("getbuycar")
})

const addData = async () => {
  store.state.buycar.forEach(async (item) => {
    const res = await $api.post(
      "http://localhost:3030/order?$limit=50",
      {
        orderid: item.id,
        ima: item.imag,
        tea: item.tea,
        money: item.money,
        ordernum: item.num,
        rating: item.rating,
        totalNum:totalNum.value,
        totalPrice:totalPrice.value,
      },

    );
    const { status } = res;
    if (status === 201){
      store.state.buycar=[]
      return ElMessage.success("添加成功");
    } 
  })

}
// 添加购物车
const order = (item) => {
  const { id } = item;
  let record = store.state.buycar.find((n) => n.id == id);
  if (record && record.num) {
    record.num++;
  } else {
    store.state.buycar.push({
      ...item,
      num: 1,
    });
  }
};

// 计算总价 和 总数量
const totalPrice = computed(() => {
  let total = 0;
  store.state.buycar.forEach(({ money, num }) => {
    total += money * num;
  });
  return total;
});
// 计算总数量
const totalNum = computed(() => {
  let total = 0;
  store.state.buycar.forEach(({ num }) => {
    total += num;
  });
  return total;
});
// 清空购物车
const clearAllCart = () => {
  store.state.buycar = [];
};

 const jia = (id) => {
  store.state.buycar.forEach(t => {
    if (t.id == id) {
      if (!t.num) {
        t.num = 2
        or.value = t.num
      } else {
        t.num++
        or.value = t.num
        totalmoney.value = or.value * t.money

      }
    }
  })
}
const jian = (id) => {
  store.state.buycar.forEach(t => {
    console.log("t.money", t.money);
    if (t.id == id) {
      if (!t.num || t.num == 0) {
        const index = store.state.buycar.findIndex(t => t.id === id)
        // 如果找到了该商品，则从数组中删除该商品
        store.state.buycar.splice(index, 1);

      }
      // store.state.buycar = []
      if (t.num > 0) {
        t.num--
        or.value = t.num
      }
    }
  })
}




</script>

<style lang="scss">
* {
  padding: 0;
  margin: 0;
}

ul,
ol,
li {
  list-style: none;
}

img {
  width: 100%;
  height: 100%;
}

.img {
  width: 80px;
  height: 80px; 
}

.layout {
  width: 100%;
  height: 100%;
  color: black;
  // background-image: url(@/imag/背景.jpg);
  background-color: rgb(245, 245, 220);

}
h3{
  color: rgb(36, 88, 53);
  font-family: fantasy;

}
.header {
  height: 100px;
  font-size: 24px;  
}

.main {
  display: flex;
  width: 100%;
  height: 100%;
  .wrapper {
    display: flex;
    width: 1400px;
    margin-right: 10px;
    border-radius: 15px;
    flex-grow: 1;
    flex-wrap: wrap;

    .main-bottom {
      display: flex;
      ul {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;


        .tab {
          padding: 3px;
          font-size: 20px;
          justify-content: space-between;
          width: 400px;
        }
      }
    }
  }
}



.cart-list {
  width: 300px;
  font-size: 18px;

  background-color: #748d79;
  border-radius: 15px;
}

p.order {
  .or {
    display: flex;
    justify-content: space-around;
  }
}
.btn{
  width: 100px;
  height: 30px;
  color: black;
  background-color: white;
  border-radius: 15px;

}
button.el-button{
  font-size: 24px;
}
</style>